#pragma once
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
using namespace std;

// 目标：实现client与service的通信

#define EXIT(m)             \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

class NameFifo
{
public:
    NameFifo(string path, string name)
        : _path(path), _name(name)
    {
        _fd = -1;
        _PATH = _path + "/" + _name;
    }

    // 创建管道
    void Create()
    {
        int n = mkfifo(_PATH.c_str(), 0666);
        if (n < 0)
        {
            EXIT("mkfifo");
        }
        cout << "命名管道创建成功！\n";
    }

    // 打开管道
    void OpenForRead()
    {
        _fd = open(_PATH.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            EXIT("open");
        }
        cout << "读端打开成功！\n";
    }

    void OpenForWrite()
    {
        _fd = open(_PATH.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            EXIT("open");
        }
        cout << "写端打开成功！\n";
    }

    // 读取数据
    void Read()
    {
        char buffer[1024];
        int n = read(_fd, buffer, sizeof(buffer) - 1);
        buffer[n] = 0;
        printf("接收到数据：%s\n", buffer);
    }

    // 写数据
    void Write()
    {
        string msg;
        cout << "请输入内容：\n";
        cin >> msg;
        write(_fd, msg.c_str(), msg.size());
    }

    // 关闭管道
    void Close()
    {
        close(_fd);
        unlink(_PATH.c_str());
        cout << "管道：" << _fd << "关闭并删除！\n";
    }

private:
    string _path;
    string _name;
    string _PATH;
    int _fd;
};